//const secp256k1 = require("@noble/secp256k1");
const secp256k1_2 = require('secp256k1');
const {keccak_256} = require("js-sha3");
const {DataUtils} = require("./data_utils");
const CryptoJS = require('crypto-js');


class ECDSAUtils {
    static sign(data,privateKeyHex)
    {
        const signature = secp256k1_2.ecdsaSign(data, DataUtils.hexToArray(privateKeyHex),{
                    recovered: true,
                    canonical: true
                }
            );
        // 获取签名的r、s值和恢复因子v
        /*const r = signature.signature.slice(0, 32);
        const s = signature.signature.slice(32, 64);
        const v = signature.recid ;
        var sighex =  DataUtils.arrayToHex(r)+DataUtils.arrayToHex(s);*/
        var sighex =  DataUtils.arrayToHex(signature.signature);
        sighex = sighex + DataUtils.numToHex(signature.recid,1);
        //var sign2 = this.sign_ex(data, privateKeyHex)

        return sighex;
    }

/*
    static sign_ex(data, privateKeyHex) {
        const [ sigDer, recid ]  = secp256k1.signSync(data, privateKeyHex, {
            recovered: true,
            canonical: true
        });

        const sig = secp256k1.Signature.fromHex(sigDer);
        var r = DataUtils.numToHex(sig.r,32);
        var s = DataUtils.numToHex(sig.s,32);
        var v = DataUtils.numToHex(recid,1);
        var result = r+s+v;
        if(result.length!=130){
            //可能有错误
            console.log("sig",sig);
            console.log("r:",r);
            console.log("s:",s);
            console.log("v:",v);
        }
        return result;

    }*/

    //计算hash，todo:国密实现，用国密js库或wasm
    //返回的hex串，不带0x前缀
    static calc_hash(bytesdata) {
        var hash = keccak_256(bytesdata);
        return hash;
    }
}

module.exports.ECDSAUtils = ECDSAUtils;